package questions;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.OpenOption;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 外部排序，
 * 比如：20g的文件，
 */
public class OuterSortDemo {
    public static void main(String[] args) {
//        prepareHugeFile("d://big_int_file.txt",1500000000);
        sort("D:\\java-demo\\big_int_file.txt",1000);
    }

    private static void sort(String file, Integer parallel) {
        File file1=new File(file);
        if (!file1.exists()){
            System.out.println("文件不存在！");
            return;
        }

        ThreadPoolExecutor executor = new ThreadPoolExecutor(6, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(200)
                , Executors.defaultThreadFactory(), (r, executor1) -> {
                    while (executor1.getQueue().remainingCapacity()<=0){
                        System.out.println(r+"开始等待入队");
                        try {
                            TimeUnit.MILLISECONDS.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(r+"入队成功");
                    executor1.execute(r);
                });


    }

    private static void prepareHugeFile(String big_int_file, int size) {
        Random random = new Random();
        File file = new File(big_int_file);
        if (file.exists()){
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            System.out.println("初始化数据文件失败");
            return;
        }
        try(FileWriter writer =new FileWriter(file)) {
            while (size-->0){
                writer.write(String.valueOf(random.nextInt(Integer.MAX_VALUE)));
                writer.append(System.lineSeparator());
                writer.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
